"""
通用Web组件
提供Web界面的通用功能和工具函数
"""

import streamlit as st
import httpx
import asyncio
from typing import Dict, Any, Optional
from datetime import datetime
import json
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from services.data_service import DataService


def load_css():
    """加载自定义CSS样式"""
    css = """
    <style>
    .main {
        padding-top: 1rem;
    }
    
    .metric-card {
        background: white;
        padding: 1rem;
        border-radius: 0.5rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.12);
        border-left: 4px solid #1f77b4;
    }
    
    .status-success {
        color: #28a745;
        font-weight: bold;
    }
    
    .status-warning {
        color: #ffc107;
        font-weight: bold;
    }
    
    .status-error {
        color: #dc3545;
        font-weight: bold;
    }
    
    .sidebar .sidebar-content {
        background: #f8f9fa;
    }
    
    .stButton > button {
        width: 100%;
        border-radius: 0.5rem;
        border: none;
        background: linear-gradient(90deg, #1f77b4, #17a2b8);
        color: white;
        font-weight: bold;
        transition: all 0.3s;
    }
    
    .stButton > button:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }
    
    .dataframe {
        border: none !important;
    }
    
    .dataframe th {
        background: #f8f9fa !important;
        color: #495057 !important;
        font-weight: bold !important;
    }
    
    .alert-success {
        background: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
        padding: 0.75rem 1.25rem;
        border-radius: 0.25rem;
        margin: 1rem 0;
    }
    
    .alert-warning {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        color: #856404;
        padding: 0.75rem 1.25rem;
        border-radius: 0.25rem;
        margin: 1rem 0;
    }
    
    .alert-error {
        background: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
        padding: 0.75rem 1.25rem;
        border-radius: 0.25rem;
        margin: 1rem 0;
    }
    </style>
    """
    st.markdown(css, unsafe_allow_html=True)


def show_alert(message: str, alert_type: str = "info"):
    """显示警告框"""
    alert_class = f"alert-{alert_type}"
    st.markdown(
        f'<div class="{alert_class}">{message}</div>',
        unsafe_allow_html=True
    )


def format_number(value: float, precision: int = 2, suffix: str = "") -> str:
    """格式化数字显示"""
    if abs(value) >= 1e9:
        return f"{value/1e9:.{precision}f}B{suffix}"
    elif abs(value) >= 1e6:
        return f"{value/1e6:.{precision}f}M{suffix}"
    elif abs(value) >= 1e3:
        return f"{value/1e3:.{precision}f}K{suffix}"
    else:
        return f"{value:.{precision}f}{suffix}"


def format_percentage(value: float, precision: int = 2) -> str:
    """格式化百分比显示"""
    return f"{value:.{precision}f}%"


def format_currency(value: float, currency: str = "¥") -> str:
    """格式化货币显示"""
    return f"{currency}{format_number(value)}"


def get_system_status() -> Dict[str, Any]:
    """获取系统状态"""
    data_service = DataService()
    return data_service.get_system_status()


def get_api_data(endpoint: str, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
    """获取API数据 - 使用统一数据服务"""
    data_service = DataService()
    
    # 根据endpoint路由到相应的数据服务方法
    if endpoint.startswith('/market'):
        if 'quotes' in endpoint:
            return data_service.get_market_quotes()
        elif 'kline' in endpoint:
            symbol = params.get('symbol', 'AAPL') if params else 'AAPL'
            period = params.get('period', '1d') if params else '1d'
            return data_service.get_market_kline(symbol, period)
    elif endpoint.startswith('/trading'):
        if 'orders' in endpoint:
            return data_service.get_trading_orders()
        elif 'positions' in endpoint:
            return data_service.get_trading_positions()
    elif endpoint.startswith('/strategies'):
        return data_service.get_strategies()
    elif endpoint.startswith('/portfolio'):
        return data_service.get_portfolio_summary()
    elif endpoint.startswith('/risk'):
        return data_service.get_risk_metrics()
    
    # 默认使用原有的HTTP客户端
    try:
        with httpx.Client(timeout=10.0) as client:
            url = f"http://localhost:8000/api/v1{endpoint}"
            response = client.get(url, params=params or {})
            if response.status_code == 200:
                return response.json()
            else:
                st.error(f"API请求失败: {response.status_code}")
                return None
    except Exception as e:
        st.error(f"连接API失败: {e}")
        return None


def post_api_data(endpoint: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """发送API数据 - 使用统一数据服务"""
    data_service = DataService()
    
    # 根据endpoint路由到相应的数据服务方法
    if endpoint.startswith('/strategies') and 'create' in endpoint:
        return data_service.create_strategy(data)
    elif endpoint.startswith('/trading/orders'):
        return data_service.create_order(data)
    
    # 默认使用原有的HTTP客户端
    try:
        with httpx.Client(timeout=10.0) as client:
            url = f"http://localhost:8000/api/v1{endpoint}"
            response = client.post(url, json=data)
            if response.status_code in [200, 201]:
                return response.json()
            else:
                st.error(f"API请求失败: {response.status_code}")
                return None
    except Exception as e:
        st.error(f"发送API数据失败: {e}")
        return None


def create_sidebar():
    """创建侧边栏导航"""
    with st.sidebar:
        st.title("🚀 AIQuant")
        st.markdown("---")
        
        # 导航菜单
        pages = {
            "🏠 主仪表板": "dashboard.py",
            "📊 数据管理": "pages/data_management.py",
            "🎯 策略管理": "pages/strategy_management.py",
            "💹 交易监控": "pages/trading_monitor.py",
            "📈 持仓分析": "pages/portfolio_analysis.py",
            "⚠️ 风险监控": "pages/risk_monitor.py",
            "📋 报告查看": "pages/reports.py",
            "⚙️ 系统设置": "pages/settings.py"
        }
        
        for name, page in pages.items():
            if st.button(name, use_container_width=True):
                st.switch_page(page)
        
        st.markdown("---")
        
        # 系统状态
        st.subheader("系统状态")
        status = get_system_status()
        
        if status["healthy"]:
            st.success("系统运行正常")
        else:
            st.error("系统异常")
        
        st.metric("活跃智能体", f"{status['active_agents']}/{status['total_agents']}")
        st.metric("运行工作流", status["running_workflows"])
        
        # 快速操作
        st.markdown("---")
        st.subheader("快速操作")
        
        if st.button("🔄 刷新数据", use_container_width=True):
            st.rerun()
        
        if st.button("📥 导出报告", use_container_width=True):
            st.info("报告导出功能开发中...")
        
        if st.button("🔧 系统维护", use_container_width=True):
            st.info("系统维护功能开发中...")


def show_loading(message: str = "加载中..."):
    """显示加载状态"""
    with st.spinner(message):
        return st.empty()


def confirm_action(message: str, key: str) -> bool:
    """确认操作对话框"""
    if f"confirm_{key}" not in st.session_state:
        st.session_state[f"confirm_{key}"] = False
    
    if not st.session_state[f"confirm_{key}"]:
        st.warning(message)
        col1, col2 = st.columns(2)
        with col1:
            if st.button("确认", key=f"yes_{key}"):
                st.session_state[f"confirm_{key}"] = True
                st.rerun()
        with col2:
            if st.button("取消", key=f"no_{key}"):
                return False
        return False
    else:
        st.session_state[f"confirm_{key}"] = False
        return True


def display_json(data: Dict[str, Any], title: str = "JSON数据"):
    """显示JSON数据"""
    with st.expander(title):
        st.json(data)


def create_download_button(data: str, filename: str, label: str = "下载"):
    """创建下载按钮"""
    st.download_button(
        label=label,
        data=data,
        file_name=filename,
        mime="text/plain"
    )


def validate_input(value: Any, input_type: str, required: bool = True) -> bool:
    """验证输入数据"""
    if required and (value is None or value == ""):
        st.error("此字段为必填项")
        return False
    
    if input_type == "number" and value is not None:
        try:
            float(value)
        except ValueError:
            st.error("请输入有效的数字")
            return False
    
    if input_type == "email" and value:
        if "@" not in value or "." not in value:
            st.error("请输入有效的邮箱地址")
            return False
    
    return True


def create_tabs(tab_names: list) -> list:
    """创建标签页"""
    return st.tabs(tab_names)


def show_progress(current: int, total: int, message: str = ""):
    """显示进度条"""
    progress = current / total if total > 0 else 0
    st.progress(progress, text=f"{message} ({current}/{total})")


def format_datetime(dt: datetime, format_str: str = "%Y-%m-%d %H:%M:%S") -> str:
    """格式化日期时间"""
    return dt.strftime(format_str)


def get_color_by_value(value: float, thresholds: Dict[str, float]) -> str:
    """根据数值获取颜色"""
    if value >= thresholds.get("good", 80):
        return "#28a745"  # 绿色
    elif value >= thresholds.get("warning", 60):
        return "#ffc107"  # 黄色
    else:
        return "#dc3545"  # 红色